//
//  ORPublicTool.m
//  BaidiMall
//
//  Created by 欧阳荣 on 2017/7/6.
//  Copyright © 2017年 欧阳荣. All rights reserved.
//

#import "ORPublicTool.h"
#import "ProgressHUD.h"

@implementation ORPublicTool

+ (BOOL)checkIsNilForTextFields:(NSArray<UITextField *> *)fields nilIndex:(void (^)(NSInteger))nilIndex{
    
    for (int i = 0; i < fields.count; i ++) {
        if (fields[i].text.length <= 0) {
            if (nilIndex) {
                nilIndex(i);
            }
            return YES;
        }
    }
    return NO;
}

+ (BOOL)checkIsNilForTextFields:(NSArray<UITextField *> *)fields {
    
    for (UITextField *field in fields) {
        if (field.height > 5 && field.text.length <= 0) {
            [ProgressHUD show:field.placeholder];
            return YES;
        }
    }
    return NO;
}

//需要WXApi
//+ (void)wxapiSharedScene:(int)scene title:(NSString *)titel image:(UIImage *)image description:(NSString *)description url:(NSString *)url {
//
//
//    if (image.size.width > 200 || image.size.height > 200) {
//        image = [self imageScale:image size:CGSizeMake(200, 200)];
//    }
//
//    //创建发送对象实例
//    SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init];
//    sendReq.bText = NO;//不使用文本信息
//    sendReq.scene = scene;//0 = 好友列表 1 = 朋友圈 2 = 收藏
//
//    //创建分享内容对象
//    WXMediaMessage *urlMessage = [WXMediaMessage message];
//    urlMessage.title = titel;//分享标题
//    urlMessage.description = description;//分享描述
//    [urlMessage setThumbImage:image];
//
//    //创建多媒体对象
//    WXWebpageObject *webObj = [WXWebpageObject object];
//    webObj.webpageUrl = url;//分享链接
//
//    //完成发送对象实例
//    urlMessage.mediaObject = webObj;
//    sendReq.message = urlMessage;
//
//    //发送分享信息
//    [WXApi sendReq:sendReq];
//
//}

/// 压缩图片尺寸,方便上传服务器
+ (UIImage *)imageScale:(UIImage *)img size:(CGSize)size{
    if (img.size.width <= size.width) {
        return img;
    }
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

+ (BOOL)IsIdentityCard:(NSString *)IDCardNumber
{
    if (IDCardNumber.length <= 0) {
        return NO;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:IDCardNumber];
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
}

+ (void)callPhoneWithPhoneNumber:(NSString *)phoneNumber {
    
    if (phoneNumber.length <= 0) {
        NSLog(@"tool : phonenumber Error");
        [ProgressHUD show:@"phonenumber Error"];
        return;
    }
    {
        static int retap = 1;
        if (retap != 1) { return; }
        retap = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            retap = 1;
        });
    }
    [ProgressHUD show:@"请稍后..."];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNumber]];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:url]];
    [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
//        [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly : @YES} completionHandler:nil];
}


+ (BOOL)IskeyWords:(NSString *)Words{
    if (Words.length <= 0) {
        return NO;
    }
    NSString *regex = @"^[a-zA-Z0-9]*$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [predicate evaluateWithObject:Words];
}
//判断不全是数字
+ (BOOL)IscheckPassWord:(NSString *)word;
{
    //6-20位数字和字母组成
    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$";
    NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:word];
}

/*
 位置： 居左/右   局上/下
 大小： 宽   和  高
 */
+ (CGFloat)calculateWidthWithString:(NSString *)string height:(CGFloat)height font:(UIFont *)font {
    return [string boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:NULL].size.width;
}

+ (NSString *)folderSizeForCache {
    CGFloat folderSize = 0.0;
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    
    NSLog(@"文件数：%ld",files.count);
    
    for(NSString *path in files) {
        
        NSString*filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
        
        folderSize += [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    CGFloat sizeM = folderSize /1024.0/1024.0;
    
    return [NSString stringWithFormat:@"%.1fM",sizeM];
}

+ (void)removeCache {
    NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
    
    NSArray*files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
    
    NSLog(@"文件数：%ld",[files count]);
    for(NSString *p in files){
        NSError*error;
        
        NSString*path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        
        if([[NSFileManager defaultManager]fileExistsAtPath:path])
        {
            BOOL isRemove = [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
            if(isRemove) {
                
            }else{
                
            }
        }
    }
}

+ (void)showAlert:(NSString *)title message:(NSString *)msg okAction:(void (^)())block {
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (block) {
            block();
        }
    }]];
    
    UIViewController * rootVC = [[UIApplication sharedApplication].delegate  window].rootViewController;
    [rootVC presentViewController:alert animated:true completion:nil];
    
}

@end
